<template>
  <el-upload class="upload-demo"
             ref="upload"
             :accept='accept'
             :action="action"
             :limit="limit"
             :list-type='uploadType'
             :headers="headers"
             :data="paramData"
             :file-list='fileList'
             :before-upload='handleUpload'
             :on-remove="handleRemove"
             :disabled="flieLoading"
             :on-success="successLoad"
             :on-error="errorLoad"
             :on-exceed="handleExceed">
    <el-button type="success"
               :loading="flieLoading1"
               @click="clickLoad"
               size="small">{{ title }}</el-button>
  </el-upload>
</template>

<script>
/* eslint-disable no-unused-vars */
import mixinViewModule from '@/mixins/view-module'
import minFormValidate from '@/mixins/form-validate'
import Cookies from 'js-cookie'
export default {
  mixins: [mixinViewModule, minFormValidate],
  name: '',
  props: {
    title: {
      type: String,
      default: '上传文件'
    },
    reg: {
      type: String,
      default: '.(doc|docx|pdf|ppt|pptx)$'
    },
    isLt2M: {
      type: Number,
      default: 30
    },
    accept: {
      type: String,
      default: '.pdf,.doc,.docx,.ppt,.pptx'
    },
    uploadType: {
      type: String,
      default: 'text'
    },
    flieLoading: {
      type: Boolean,
      default: false
    },
    isHealthCode: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: 10
    },
    action: {
      type: String,
      default: '/springbootApi/system/oss/upload'
    },
    initFileList: {
      type: Array,
      default: () => []
    },
    paramData: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      mixinViewModuleOptions: {
        getDataListURL: '', // 数据列表接口，API地址
        getDataListIsPage: true, // 数据列表接口，是否需要分页？
        addOrUpdateURL: '', // 添加或修改接口，API地址
        getDataInfoURL: '', // 数据详情，API地址
        deleteIsBatch: true, // 删除接口，是否需要批量？
        exportURL: '' // 导出接口，API地址
      },
      flieLoading1: false,
      // paramData: {
      //   type: 2
      // },
      dataForm: {},
      fileList: [],
      headers: {
        token: Cookies.get('housekeeperToken')
      }
    }
  },
  components: {},
  computed: {},
  watch: {
    initFileList: {
      handler: function (nVal) {
        this.fileList.splice(0, this.fileList.length, ...nVal)
      },
      immediate: true
    }
  },
  beforeDestroy () {
    this.$refs.upload.abort()
  },
  beforeRouteLeave (to, from) {
    // 在导航离开渲染该组件的对应路由时调用
    this.$refs.upload.abort()
  },
  methods: {
    init (data) {
      this.fileList.splice(0, this.fileList.length, ...data)
    },
    // 上传成功
    successLoad (response, file, fileList) {
      this.flieLoading1 = false
      if (response.code === 0) {
        if (this.uploadType !== 'text') {
          this.fileList.push({
            name: file.name,
            url: `${response.data}`
          })
        } else {
          this.fileList.push({
            name: file.name,
            url: response.data
          })
        }

        this.$emit('success', file.name, response.data)
      } else {
        this.$message.error({
          message: response.msg
        })
        if (this.isHealthCode) {
          this.fileList = []
        }
      }
    },
    // 文件校验
    handleUpload (file) {
      this.$emit('handleUpload')
      const patt = new RegExp(this.reg, 'i')
      const pattImg = new RegExp('.(png|jpeg|jpg)$', 'i')
      // const isLt2M = file.size / 1024 / 1024 < 20
      const isLt2M = file.size / 1024 / 1024 < this.isLt2M
      // console.log(pattImg.test(file.name))

      // if (pattImg.test(file.name)) {
      //   this.paramData.type = 0
      // }
      // if (file.name.indexOf('.apk') !== -1) {
      //   this.paramData.type = 3
      // }
      if (!patt.test(file.name)) {
        this.$message.warning(`上传文件中存在非${this.accept}文件`)
        return false
      }
      if (!isLt2M) {
        this.$message.warning(`上传文件的大小不能超过${this.isLt2M}M`)
        return false
      }
      if (pattImg.test(file.name) && !isLt2M) {
        this.$message.warning(`上传图片的大小不能超过20M`)
        return false
      }
      this.flieLoading1 = true
    },
    handleExceed (files, fileList) {
      this.$message.warning(`当前限制选择 ${this.limit} 个文件`)
    },
    clickLoad () {
      this.$emit('clickImg')
    },
    // 监听是否删除文件
    // handleRemove (file, list) {
    //   this.flieLoading = false
    //   let num = 0
    //   const item = this.fileList.filter((item, index) => {
    //     let bool = item.url === file.url
    //     if (bool) { num = index }
    //     return bool
    //   })

    //   if (item.length) {
    //     this.fileList.splice(num, 1)

    //     if (this.uploadType !== 'text') {
    //       // let src = item[0].url.split('?')[0]
    //       let src = item[0].url.split('housekeeper')[1]
    //       src = `housekeeper${src}`
    //       item[0].url = src
    //     }

    //     this.$emit('remove', item[0], num)
    //   }
    // },
    handleRemove (file, list) {
      let num = 0
      const item = this.fileList.filter((item, index) => {
        let bool = item.url === file.url
        if (bool) { num = index }
        return bool
      })

      if (item.length) {
        this.fileList.splice(num, 1)
        this.$emit('remove', item[0], num)
      }
    },
    // 提交失败
    errorLoad (response, file, fileList) {
      this.flieLoading1 = false
      this.$message({
        message: '提示， 提交失败！',
        type: 'error'
      })
    }
  }
}
</script>

<style lang="scss" scoped></style>
